package com.hui.dbmigrator.controller;

import com.hui.dbmigrator.dto.request.MigrationRequest;
import com.hui.dbmigrator.dto.response.ApiResponse;
import com.hui.dbmigrator.entity.TableDefinition;
import com.hui.dbmigrator.handler.DatabaseHandler;
import com.hui.dbmigrator.service.DatabaseService;
import com.hui.dbmigrator.service.MigrationService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/migrations")
@RequiredArgsConstructor
public class MigrationController {

    private final MigrationService migrationService;
    private final DatabaseService databaseService;

    @PostMapping
    public ApiResponse<String> migrateTable(
            @RequestBody @Valid MigrationRequest request) {

        try {
            String ddl = migrationService.migrateTable(request);
            return ApiResponse.success(ddl);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/preview")
    public ApiResponse<String> previewMigration(
            @RequestBody @Valid MigrationRequest request) {

        try {
            DatabaseHandler sourceHandler = databaseService.getHandler(request.getSource().getType().getDisplayName());
            DatabaseHandler targetHandler = databaseService.getHandler(request.getTarget().getType().getDisplayName());

            TableDefinition sourceTable = sourceHandler.extractTable(
                    request.getTableName(), request.getSource());

            TableDefinition targetTable = migrationService.convertTable(
                    sourceTable,
                    request.getSource().getType().getDisplayName(),
                    request.getTarget().getType().getDisplayName());

            return ApiResponse.success(targetHandler.generateCreateTable(targetTable));
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}
